<template >
    <div class="menu-check">
        <el-input v-model="keyword" placeholder="请输入关键字" />
        <div class="menu-check-box">
            <el-tree ref="tree" show-checkbox :data="data" :props="defaultProps" node-key="id"
                :filter-node-method="filterNode" />
        </div>
    </div>
</template>

<script>
import { getMenuList } from "@/api/menu";
import { deepTree, isLeaf } from "@/utils/index";

export default {
    name: "menu-check",
    data() {
        return {
            // 关键字
            keyword: '',
            // menuList 数据
            list: [],
            defaultProps: {
                label: 'name',
                children: 'children',
            },
        };
    },

    computed: {
        // Tree组件需要的数据
        data() {
            // 将扁平化的数组data转化为树形结构数据
            return deepTree(this.list);
            // console.log(treeData);
        }
    },

    watch: {
        keyword(value) {
            this.$refs.tree.filter(value)
        }
    },

    methods: {
        refresh() {
            getMenuList().then(data => {
                console.log('refresh then');
                this.list = data;
                console.log('data1',data);
                this.$emit('ok')
            })
        },

        filterNode(value, data) {
            return data.name.includes(value)
        },

        // 获取当前勾选框的集合后，包含选中与半选中
        get() {
            const key1 = this.$refs.tree.getCheckedNodes();
            const key2 = this.$refs.tree.getHalfCheckedKeys();
            return [...key1, ...key2]
        },
        set(keys) {
            console.log(this.list.length);
            // 将非叶子节点过滤除去
            const newKeys = keys.filter(id => isLeaf(this.list, id))
            this.$refs.tree.setCheckedKeys(newKeys);
        },

        fn1() {
            console.log(this.$refs.tree.getCheckedNodes());
            console.log(this.$refs.tree.getCheckedKeys());
            console.log(this.$refs.tree.getHalfCheckedKeys())
        },
        fn2() {
            this.$refs.tree.filter('4')
        },
    },
    created() {
        this.refresh()
    }
};
</script>

<style lang="scss" scoped>
.menu-check {
    flex: 1;

    &-box {
        margin-top: 10px;
        border: 1px solid #dcdfe6;
        border-radius: 4px;
        padding: 5px 0;
        background-color: #fff;
    }
}
</style>